package com.qike.duola.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qike.duola.domain.*;
import com.qike.duola.dto.MessageListDto;
import com.qike.duola.dto.MsgAddDto;
import com.qike.duola.enums.*;
import com.qike.duola.mapper.DuolaMessageMapper;
import com.qike.duola.mapper.SysUserMapper;
import com.qike.duola.service.DuolaLineService;
import com.qike.duola.service.DuolaMessageService;
import com.qike.duola.socket.NewMessageSocket;
import com.qike.duola.utils.TimeTool;
import com.qike.duola.vo.MessageList;
import com.qike.duola.vo.MessageListVo;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Eric.zhou
 * @Date: 2020/10/12 16:18
 */
@Service
public class DuolaMessageServiceImpl implements DuolaMessageService {
    private static final Logger logger = LoggerFactory.getLogger(DuolaMessageServiceImpl.class);

    @Autowired
    private DuolaMessageMapper messageMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private NewMessageSocket messageSocket;



    /**
     * 发送消息
     *
     * @param msgAddDto
     */
    @Override
    @Async
    public void msgAdd(MsgAddDto msgAddDto) throws IOException {
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info(userId+"发送消息"+ JSON.toJSON(msgAddDto));
        DuolaMessage duolaMessage = new DuolaMessage();
        duolaMessage.setAddTime(LocalDateTime.now());
        duolaMessage.setAddUid(userId);
        SysUserWithBLOBs sysUserWithBLOBs = sysUserMapper.selectByPrimaryKey(userId);
        duolaMessage.setAddName(sysUserWithBLOBs.getNickname());
        duolaMessage.setContent(msgAddDto.getContent());
        duolaMessage.setMsgType(msgAddDto.getMsgType());
        duolaMessage.setTitle(msgAddDto.getTitle());
        duolaMessage.setOriginType(msgAddDto.getOriginType());
        duolaMessage.setReceiveUid(msgAddDto.getSendUid());
        duolaMessage.setIsRead(IsReadStatusEnums.NO.getEcode());
        messageMapper.insert(duolaMessage);
        List<MessageList> list = new ArrayList<>();
        DuolaMessageExample example = new DuolaMessageExample();
        example.createCriteria().andReceiveUidEqualTo(userId);
        example.setOrderByClause("add_time desc");
        List<DuolaMessage> duolaMessages = messageMapper.selectByExample(example);
        for (DuolaMessage message : duolaMessages) {
            MessageList messageList = new MessageList();
            messageList.setId(message.getId());
            messageList.setAddTime(TimeTool.LocalDateTimeFormat(message.getAddTime()));
            messageList.setIsRead(message.getIsRead());
            messageList.setTitle(message.getTitle());
            messageList.setContent(message.getContent());
            messageList.setOriginType(message.getOriginType());
            messageList.setOriginId(message.getOriginId());
            list.add(messageList);
        }
        messageSocket.sendMessage(JSON.toJSONString(list),msgAddDto.getSendUid().intValue());
    }

    /**
     * 消息列表
     *
     * @param messageListDto
     * @return
     */
    @Override
    public MessageListVo messageList(MessageListDto messageListDto) {
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info(userId+"消息列表"+ JSON.toJSON(messageListDto));
        MessageListVo vo = new MessageListVo();
        List<MessageList> list = new ArrayList<>();

        DuolaMessageExample example = new DuolaMessageExample();
        DuolaMessageExample.Criteria criteria = example.createCriteria().andReceiveUidEqualTo(userId);
        if (messageListDto.getType()!=null){
            criteria.andMsgTypeEqualTo(messageListDto.getType());
        }
        example.setOrderByClause("add_time desc");
        Page page = PageHelper.startPage(messageListDto.getStartPage(), messageListDto.getPageSize());
        List<DuolaMessage> duolaMessages = messageMapper.selectByExample(example);
        for (DuolaMessage duolaMessage : duolaMessages) {
            MessageList messageList = new MessageList();
            messageList.setId(duolaMessage.getId());
            messageList.setAddTime(TimeTool.LocalDateTimeFormat(duolaMessage.getAddTime()));
            messageList.setIsRead(duolaMessage.getIsRead());
            messageList.setTitle(duolaMessage.getTitle());
            messageList.setContent(duolaMessage.getContent());
            messageList.setOriginType(duolaMessage.getOriginType());
            messageList.setOriginId(duolaMessage.getOriginId());
            list.add(messageList);
        }
        vo.setList(list);
        vo.setTotal(page.getTotal());
        return vo;
    }

    /**
     * 读取消息
     *
     * @param ids
     */
    @Override
    public void readMsg(List<Integer> ids) {
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info(userId+"读取消息"+ JSON.toJSON(ids));
        DuolaMessageExample example = new DuolaMessageExample();
        DuolaMessageExample.Criteria criteria = example.createCriteria().andReceiveUidEqualTo(userId);
        if (ids!=null&&ids.size()>0){
            criteria.andIdIn(ids);
        }
        DuolaMessage duolaMessage = new DuolaMessage();
        duolaMessage.setIsRead(IsReadStatusEnums.YES.getEcode());
        duolaMessage.setReadTime(LocalDateTime.now());
        messageMapper.updateByExampleSelective(duolaMessage,example);
    }

    /**
     * 给全体人员发送消息
     *
     * @param title
     * @param sendId
     * @param msgType
     * @throws IOException
     */
    @Override
    @Async
    public void allUserMsgAdd(Integer originId,String title, Long sendId, Integer msgType) throws IOException {
        SysUserExample userExample = new SysUserExample();
        userExample.createCriteria().andStatusEqualTo(StatusEnums.NO.getEcode());
        List<SysUser> sysUsers = sysUserMapper.selectByExample(userExample);
        for (SysUser sysUser : sysUsers) {
            MsgAddDto msgAddDto = new MsgAddDto();
            msgAddDto.setTitle(MessageTitleEnums.ACTIVE.getEmsg());
            msgAddDto.setMsgType(MessageTypeEnums.active.getEcode());
            msgAddDto.setOriginId(originId);
            msgAddDto.setSendUid(sysUser.getId());
            this.msgAdd(msgAddDto);
        }
    }
}
